package com.android2024.no6_music;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/** 本地音乐数据  **/
public class MusicData implements Callback {
    //对存储空间的读写权限
    final static String[] permArr = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };
    //上下文句柄
    Context context;

    public MusicData(Context context){
        this.context = context;
        if(!JwPermissions.isHavePermissions(this.context,MusicData.permArr)){
            //已经分配权限 初始化应用数据
            init();
        }else //未分配权限 动态申请权限
        JwPermissions.permissions(this.context,1,permArr);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        Log.d("log","### onFailure "+e.toString());
        //Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG);
        Message msg = new Message();
        msg.what = 1;
        MainActivity.handler.sendMessage(msg);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String json = response.body().string();
        Log.d("log","### onResponse "+json);
        ArrayList<Music> list;
        Gson gson = new Gson();
        TypeToken<ArrayList<Music>> token = new TypeToken<ArrayList<Music>>(){};
        list = gson.fromJson(json,token.getType());
        if(list!=null)
            musics.addAll(list);
    }

    static final String[] SRCS={"应用","本地","网络"};
    //音乐数据结构
    class Music
    {
        String name="",song="",zj="",url="";
        int type=0,rawid=0;
        /*
        //歌曲ID：MediaStore.Audio.Media._ID,,
        public int id;
        //歌曲的总播放时长
        public int duration;
        //歌曲文件的大小
        public long size;
        //歌曲的名称,歌曲的专辑名,歌曲的歌手名,歌曲文件的路径
        public String tilte,album,artist,url;
        //专辑图片
        public Bitmap bitmap;
        */
        //将歌曲信息显示到布局中
        public void setView(View view){
            TextView tilteView = view.findViewById(R.id.name);
            TextView albumView = view.findViewById(R.id.album);
            ImageView imageView = view.findViewById(R.id.image);
            tilteView.setText("来源:"+SRCS[type]+" "+name);
            albumView.setText(song+":"+zj);
            /*
            if(bitmap!=null){
                imageView.setImageDrawable(new BitmapDrawable(bitmap));
            }*/
        }
    }

    //用链表保存本地所以音乐数据
    ArrayList<Music> musics = new ArrayList<>();

    //当前选择的音乐
    Music chooseMusic = null;

    final static String httpurl="http://172.16.1.2:8080";

    private void initNet(){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(httpurl+"/myapp/music.json").build();
        Call call = client.newCall(request);
        call.enqueue(this);
    }
    //初始化音乐数据 获得本地音乐数据并保存到链表中
    public void init(){
        //initSD();
        initNet();
        //默认选择第一首音乐
        if(musics.size()>0)
            setChooseMusic(musics.get(0));
    }

    private void initSD(){
        //通过内容提供者获取音乐列表
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor=contentResolver.query(uri,null,null,null,null);
        while(cursor.moveToNext())
        {
            //将数据库数据设置给外部数据
            Music tData = new Music();
            //tData.id=cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
            tData.name=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
            tData.zj=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
            tData.song=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
            tData.url=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
            //tData.duration=cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
            //tData.size=cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
            //tData.bitmap = getImage(tData.url);
            tData.type = 1;
            musics.add(tData);
        }
        cursor.close();
    }
    /** 选中音乐 **/
    public void setChooseMusic(Music chooseMusic) {
        this.chooseMusic = chooseMusic;
    }

    /** 获得选中音乐 **/
    public Music getChooseMusic() {
        return chooseMusic;
    }

    /** 获得所有的音乐 **/
    public ArrayList<Music> getMusics() {
        return musics;
    }

    /** 选择上一首音乐 **/
    public void last(){
        int id = musics.indexOf(chooseMusic);
        id--;
        if(id<0) id=musics.size()-1;
        setChooseMusic(musics.get(id));
    }

    /**选择下一首音乐 **/
    public void next(){
        int id = musics.indexOf(chooseMusic);
        id++;
        if(id>=musics.size()) id=0;
        setChooseMusic(musics.get(id));
    }

    /** 获得歌曲的专辑图片 **/
    private Bitmap getImage(String url) {
        Bitmap bitmap=null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(url);
        byte[] data = retriever.getEmbeddedPicture();
        if(data!=null){
            bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
        }
        return bitmap;
    }
}
